<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">AI学习系统登录界面</h2>
      <el-form
        :model="loginForm"
        :rules="rules"
        ref="loginFormRef"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="userName">
          <el-input
            v-model="loginForm.userName"
            placeholder="请输入用户名"
            prefix-icon="User"
            clearable
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleLogin"
            style="width: 100%"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axiosObject from "@/main.js";

const router = useRouter()
const loginFormRef = ref(null)
const loginForm = reactive({
  userName: 'admin',
  password: '123'
})

const rules = reactive({
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 12, message: '长度在3到12个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 18, message: '长度在3到18个字符', trigger: 'blur' }
  ]
})

const handleLogin = () => {
  loginFormRef.value.validate(async valid => {
    if (!valid) return;

    // 发送登录请求
    const result = await axiosObject.post("/login", loginForm);

    if (result.data.code !== 200) {
      // 登录失败提示
      setTimeout(() => {
        ElMessage.error(result.data.errorMessage || '登录失败，请检查账号密码');
      }, 500);
    } else {
      // 登录成功处理
      setTimeout(() => {
        ElMessage.success('登录成功');

        // 1. 存储完整用户信息（原逻辑保留）
        localStorage.setItem("loginAdmin", JSON.stringify(result.data.resultData));

        // 2. 单独存储userId（关键新增逻辑）
        if (result.data.resultData && result.data.resultData.id) {
          localStorage.setItem("userId", result.data.resultData.id);
        } else {
          console.warn("登录响应中未包含用户ID，可能导致个人中心无法加载");
        }

        // 3. 存储token（如果后端返回了token）
        if (result.data.token) {
          localStorage.setItem("token", result.data.token);
        }

        // 跳转到首页或个人中心
        router.push('/dashboard');
      }, 1000);
    }
  });
};
// 2. 退出登录方法
const logout = async () => {
  try {
    const loginData = JSON.parse(localStorage.getItem("loginAdmin") || "{}");
    if (!loginData?.loginAdmin?.id) return;

    const result = await axiosObject.get("/user/logout", {
      params: { id: loginData.loginAdmin.id }
    });

    if (result.data.code === 200) {
      localStorage.removeItem("loginAdmin");
      ElMessage.success("退出成功");
      window.location.href = "/login";
    } else {
      ElMessage.error(result.data.msg || "退出失败");
    }
  } catch (error) {
    console.error("退出请求异常：", error);
    ElMessage.error("网络异常，请稍后重试");
  }
};

// 3. 更新个人信息（补充之前的 submitInfo 方法）
const submitInfo = async () => {
  const valid = await infoFormRef.value.validate().catch(() => false);
  if (!valid) return;

  try {
    const result = await axiosObject.post("/user/updateInfo", {
      userId: userInfo.id,
      ...editForm
    });

    if (result.data.code === 200) {
      Object.assign(userInfo, { ...userInfo, ...editForm });
      ElMessage.success("个人信息修改成功");
    } else {
      ElMessage.error(result.data.msg || "修改失败");
    }
  } catch (err) {
    console.error("修改信息异常：", err);
    ElMessage.error("网络异常，请稍后重试");
  }
};

// 4. 上传头像（完善之前的 handleAvatarSuccess 方法）
const handleAvatarSuccess = async (res) => {
  if (res.code === 200) {
    userInfo.headPic = res.data.avatarUrl;
    // 调用更新头像接口
    const result = await axiosObject.post("/user/updateAvatar", {
      userId: userInfo.id,
      avatarUrl: res.data.avatarUrl
    });
    if (result.data.code === 200) {
      ElMessage.success("头像更新成功");
    } else {
      ElMessage.error("头像更新失败：" + result.data.msg);
    }
  } else {
    ElMessage.error("上传失败：" + (res.msg || "未知错误"));
  }
};

// 5. 保存任务笔记（完善之前的 submitNote 方法）
const submitNote = async () => {
  const valid = await noteFormRef.value.validate().catch(() => false);
  if (!valid) return;

  try {
    const result = await axiosObject.post("/task/updateNote", noteForm);
    if (result.data.code === 200) {
      const target = tasks.value.find(t => t.user_task_id === noteForm.user_task_id);
      if (target) target.notes = noteForm.notes || "无";
      noteDialogVisible.value = false;
      ElMessage.success("笔记保存成功");
    } else {
      ElMessage.error("保存失败：" + (result.data.msg || "未知错误"));
    }
  } catch (err) {
    console.error("保存笔记异常：", err);
    ElMessage.error("网络异常，请稍后重试");
  }
};

</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}
.login-card {
  width: 400px;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #409eff;
}
</style>
